package com.aduerr.v1shouyin.mvp.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import androidx.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.entity.BannerEntity;
import com.aduerr.v1shouyin.entity.CashierPermissionEntity;
import com.aduerr.v1shouyin.entity.OrderGetPosOrderLEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.activity.*;
import com.aduerr.v1shouyin.mvp.widget.BannerImageLoader;
import com.aduerr.v1shouyin.print.PrinterWrapper;
import com.aduerr.v1shouyin.unioncard.BaseUnionFragment;
import com.aduerr.v1shouyin.util.NumUtil;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.SignInDialog;
import com.orhanobut.hawk.Hawk;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2018/10/15 15:03
 * @change
 * @chang time
 * @class describe
 */

public class HomePageFragment extends BaseUnionFragment {

    @BindView(R.id.banner)
    Banner banner;

    List<String> images;
    private OrderGetPosOrderLEntity.DataBean.ListBean listBean;
    private String[] content = new String[15];
    private List<BannerEntity.DataBean> listBanner;
    private SignInDialog signInDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_page;
    }

    @Override
    protected void initBase() {
        super.initView();
        images = new ArrayList<>();
        //设置图片加载器
        banner.setImageLoader(new BannerImageLoader());
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        initDailog();
        getBannerList(mContext);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int i) {
                if(listBanner == null) return;
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra("url", listBanner.get(i).getBehavior());
                startActivity(intent);
            }
        });
    }

    @OnClick({R.id.rl_go_pos, R.id.rl_order, R.id.rl_refund, R.id.rl_trade,
            R.id.rl_print})
    void clicked(View v) {
        switch(v.getId()) {
            case R.id.rl_go_pos:
                if(Hawk.get("f_pos") == null) {
                    Hawk.put("f_pos", 1);
                } else {
                    Hawk.put("f_pos", (int) Hawk.get("f_pos") + 1);
                }

                Intent intent = new Intent(mContext, CalculatorActivity.class);
                intent.putExtra("CSAH_TYPE", CalculatorActivity.NO_CASH);
                startActivity(intent);
                break;
            case R.id.rl_order:
                if(Hawk.get("f_order") == null) {
                    Hawk.put("f_order", 1);
                } else {
                    Hawk.put("f_order", (int) Hawk.get("f_order") + 1);
//                    Log.i("TAG", "数量 ====" + Hawk.get("f_order"));
                }
                startActivity(new Intent(mContext, OrderActivity.class));
                break;
            case R.id.rl_print:
                if(Hawk.get("f_print") == null) {
                    Hawk.put("f_print", 1);
                } else {
                    Hawk.put("f_print", (int) Hawk.get("f_print") + 1);
                }
                initleftDrawaData(mContext);
                break;
            case R.id.rl_refund:
                if(Hawk.get("f_refund") == null) {
                    Hawk.put("f_refund", 1);
                } else {
                    Hawk.put("f_refund", (int) Hawk.get("f_refund") + 1);
                }
                startActivity(new Intent(mContext, RefundActivity.class));
                break;
            case R.id.rl_trade:
                if(Hawk.get("f_trade") == null) {
                    Hawk.put("f_trade", 1);
                } else {
                    Hawk.put("f_trade", (int) Hawk.get("f_trade") + 1);
                }
                String userLevel = Hawk.get("level");
                if(userLevel.equals("收银员")) {
                    checkCashierPermission();
                } else {
                    startActivity(new Intent(mContext, CheckBillActivity.class));
                }
                break;
        }
    }

    /**
     * 作用：获取收银员是否有查看对账权限
     * 说明：收银员查看对账权限不宜放在登录里因为后台随时可能更改权限，故每次点击都请求，默认没权限
     */
    public void checkCashierPermission() {
        HashMap<String, String> addParams = new HashMap<>();
        APIRetrofit.getAPIService().isCashierCanCheckBill(RXRequest.getXingPosParams(addParams, mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CashierPermissionEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CashierPermissionEntity entity) {
                        if(entity.getSuccess() == 1) {
                            boolean b = entity.isIsLookSummaryData();
                            if(b){
                                startActivity(new Intent(mContext, CheckBillActivity.class));
                            }else{
                                com.blankj.utilcode.util.ToastUtils.showShort("暂无权限！");
                            }
                        } else {
                            com.blankj.utilcode.util.ToastUtils.showShort(entity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void initleftDrawaData(Context mContext) {

        @SuppressLint("SimpleDateFormat") SimpleDateFormat sDateFormat =
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDate = sDateFormat.format(new Date());
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("page", "1");
        addParams.put("beginDate", "1970-12-08 10:00:00");
        addParams.put("endDate", currentDate);
        addParams.put("paytype", "6");

        APIRetrofit.getAPIService().orderGetPosOrderL(RXRequest.getXingPosParams(addParams, mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderGetPosOrderLEntity>() {


                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull OrderGetPosOrderLEntity orderGetPosOrderLEntity) {
                        int success = orderGetPosOrderLEntity.getSuccess();
                        if(success == 1) {
                            List<OrderGetPosOrderLEntity.DataBean> data =
                                    orderGetPosOrderLEntity.getData();
                            if(data.size() > 0) {
                                listBean = data.get(0).getList().get(0);
                                content[0] = listBean.getOrdermoney();
                                content[1] = listBean.getRealpay();
                                content[2] = listBean.getSelleryouhui();
                                content[3] = listBean.getYouhui();
                                content[4] = listBean.getUseraccount();
                                content[5] = listBean.getCreatetime();
                                content[6] = listBean.getOrderid();
                                content[7] = listBean.getOutorderid();
                                content[8] = listBean.getShopname();
                                content[9] = listBean.getSiteusername();
                                content[10] = listBean.getOrdernote();//备注ordernote
                                content[11] = listBean.getPaytype();
                                content[12] = listBean.getPaystate();
                                content[13] = Hawk.get("company");
                                content[14] = "补打小票";
                                //判断是否可以打印上一笔
                                cantoprintlastorder();

                            } else {
                                ToastUtils.showToast(mContext, "没有数据了");
                            }
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(mContext, "autologin");
                            SharedPreferencesUtils.remove(mContext, "remberpassword");
                            startActivity(new Intent(mContext, BangGuidActivity.class));
                            getActivity().finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(orderGetPosOrderLEntity.getErrMsg());
                            SharedPreferencesUtils.remove(mContext, "autologin");
                            SharedPreferencesUtils.remove(mContext, "remberpassword");
                            startActivity(new Intent(mContext, LoginActivity.class));
                            getActivity().finish();
                        } else {
                            ToastUtils.showToast(mContext,
                                    orderGetPosOrderLEntity.getErrMsg() + "");
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(mContext, "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(mContext, "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(mContext, "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    public void getBannerList(Context mContext) {
        HashMap<String, String> addParams = new HashMap<>();
        APIRetrofit.getAPIService().getBannerList(RXRequest.getXingPosParams(addParams,
                mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(bannerEntity -> {
                    listBanner = bannerEntity.getData();
                    for(BannerEntity.DataBean bean : listBanner) {
                        images.add(bean.getImgPath());
                    }
                    banner.setImages(images);
                    banner.start();
                }, throwable -> {
                    Toast.makeText(mContext, "网络异常", Toast.LENGTH_SHORT).show();
                });


    }

    private void initDailog() {

        if(Hawk.get("accountname") != null) {
            if(signInDialog != null) {
                //do nothing
            } else {
                signInDialog = new SignInDialog(getActivity(), R.style.loading_dialog,
                        new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        signInDialog.dismiss();
                    }
                });
                signInDialog.show();
                //===============================修改
//                //结算账户
                String accountName = Hawk.get("accountname");
                String bankPermitInfo = Hawk.get("BankPermitInfo");
                String bankPermitAccount = Hawk.get("BankPermitAccount");
                if(bankPermitAccount == null || bankPermitAccount.length() == 0 || !NumUtil.isNumer(bankPermitAccount)) {
                    //不显示信息 只显示绑定成功
                } else {
                    int length = bankPermitAccount.length();
                    String substringend = bankPermitAccount.substring(length - 4);
                    String substringstart = bankPermitAccount.substring(0, 4);
                    String substringmiddle = "*";
                    int a = length - 8;
                    for(int i = 0; i < a - 1; i++) {
                        substringmiddle += "*";
                    }
                    String s = substringstart + substringmiddle + substringend;
                    String level = Hawk.get("level");
                    //权限判断  财务专员是全部都显示  普通收银员显示银行信息不显示银行账户和结算银行
                    if(level.equals("财务专员")) {
                        signInDialog.setText(accountName, s, bankPermitInfo);
                    } else {
                        signInDialog.setText(accountName, "", "");
                        signInDialog.setvisbility();
                    }
                }

            }
        }

    }

    //判断是否可以打印上一笔的数据
    private void cantoprintlastorder() {

        int printpage = (int) SharedPreferencesUtils.getParam(mContext, "printpage", 1);
        if(printpage == 0) {
            ToastUtils.showToast(mContext, "打印张数设置为不打印,请先设置打印张数!!");
            return;
        }

        if(content != null && content.length > 0) {
            String paytype = listBean.getPaytype();
            Bitmap bitmap = null;
            if(paytype.equals("微信")) {
                bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.print_w);
            } else if(paytype.equals("支付宝")) {
                bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.print_z);
            } else if(paytype.equals("云闪付")) {
                bitmap = BitmapFactory.decodeResource(getResources(),
                        R.drawable.print_ysf);
            } else {
                bitmap = BitmapFactory.decodeResource(getResources(),
                        R.drawable.print_public);
            }
            print(bitmap, content, Constants.PRINT_LAST_ORDER, printpage);
        } else {
            ToastUtils.showToast(mContext, "没有数据,请完成一笔交易后重试!!!");
        }

    }


    private void print(Bitmap logo, String[] content, int orderType, int printPage) {
        printOrder(logo, content, orderType, printPage);
    }

    private void printOrder(Bitmap logo, String[] content, int orderType, int printPage) {
        PrinterWrapper.printPosOrder(logo, content, orderType, printPage);
    }
}
